package gherkinedit.wizard;

import java.util.ArrayList;
import java.util.List;

import gherkinedit.templatesystem.Template;

import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

public class InsertFromTemplateWizardPage2 extends WizardPage {
	private Composite container;
	private InsertFromTemplateWizard wizard;
	private Template choosenTemplate;
	private Label label2;
	private List<Label> labels = new ArrayList<Label>();
	private List<Text> texts = new ArrayList<Text>();

	public InsertFromTemplateWizardPage2(InsertFromTemplateWizard wizard) {
		super("Insert Template");
		setTitle("Enter Template input");
		setDescription("Enter the input for the Template");
		this.wizard = wizard;
	}

	@Override
	public void createControl(Composite parent) {
		container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 2;
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		
		Label label1 = new Label(container, SWT.NULL);
		label1.setText("Template String: ");
		label2 = new Label(container, SWT.NULL);
		label2.setText("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW");
		

		for (int i = 0; i < 15; i++) {
			Label label = new Label(container, SWT.NULL);
			label.setText("WWWWWWWWWWWW");
			labels.add(label);
			Text text = new Text(container, SWT.BORDER | SWT.SINGLE);
			text.setText("");
			text.addKeyListener(new KeyListener() {

				@Override
				public void keyPressed(KeyEvent e) {
				}

				@Override
				public void keyReleased(KeyEvent e) {
					setPageComplete(true);
				}

			});
			text.setLayoutData(gd);
			texts.add(text);
		}

		// Required to avoid an error in the system
		setControl(container);
		setPageComplete(false);
	}

	public void drawControls() {
		choosenTemplate = wizard.getChoosenTemplate();
		List<String> templateInputList = choosenTemplate.getTextInputList();
		label2.setText(choosenTemplate.templateString);
		for (int i = 0; i < 15; i++) {
			if(i<templateInputList.size()) {
				labels.get(i).setText(templateInputList.get(i));
				labels.get(i).setVisible(true);
				texts.get(i).setVisible(true);
				System.out.println("Input: " + templateInputList.get(i));
			} else {
				labels.get(i).setVisible(false);
				texts.get(i).setVisible(false);
			}
		}
		container.redraw();
	}
	
	public String getTemplateResult() {
		List<String> userInputs = new ArrayList<String>();
		for (Text text : texts) {
			if (text.isVisible()) {
				userInputs.add(text.getText());
			}
		}
		return choosenTemplate.getResultingTemplateString(userInputs);
	}
}
